package com.singularity.common.controller;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import com.singularity.common.domain.dto.permission.PermissionInfoDTO;
import com.singularity.common.domain.entity.Permission;
import com.singularity.common.domain.param.permission.PermissionAddParam;
import com.singularity.common.domain.param.permission.PermissionUpdateParam;
import com.singularity.common.service.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 天
 *
 * @description: 权限控制层
 */
@RestController
@RequestMapping("/permission")
@Api(tags = "权限相关")
public class PermissionController {

    private final PermissionService permissionService;

    @Autowired
    public PermissionController(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @ApiOperation("获取所有权限")
    @RequestMapping(method = RequestMethod.GET,value = "/permissions/{status}")
    public SaResult getPermission(@PathVariable("status") Integer status) {
        List<PermissionInfoDTO> list = permissionService.getAllPermissionList(status);
        return new SaResult(SaResult.CODE_SUCCESS,"查询成功",list);
    }

    @ApiOperation("根据角色id获取权限")
    @RequestMapping(method = RequestMethod.GET,value = "/getByRoleId/{roleId}")
    public SaResult getPermissionByRoleId(@PathVariable("roleId") Long roleId) {
        List<PermissionInfoDTO> list = permissionService.getPermissionList(roleId);
        return new SaResult(SaResult.CODE_SUCCESS,"查询成功",list);
    }

    @ApiOperation("添加菜单")
    @RequestMapping(method = RequestMethod.POST,value = "/add")
    public SaResult insertPermission(@RequestBody PermissionAddParam permissionAddParam){
        if (permissionAddParam.getPid() == null){
            permissionAddParam.setPid(0L);
        }
        permissionAddParam.setStatus(1);
        Permission permission = BeanUtil.copyProperties(permissionAddParam, Permission.class);
        Boolean insert = permissionService.insert(permission);
        if (insert){
            return SaResult.ok("添加成功");
        }
        return SaResult.error("添加失败");
    }

    @ApiOperation("修改菜单")
    @RequestMapping(method = RequestMethod.POST,value = "/update")
    public SaResult updatePermission(@RequestBody PermissionUpdateParam permissionUpdateParam){
        Permission permission = BeanUtil.copyProperties(permissionUpdateParam, Permission.class);
        Boolean insert = permissionService.update(permission);
        if (insert){
            return SaResult.ok("修改成功");
        }
        return SaResult.error("修改失败");
    }
}
